home *** CD-ROM | disk | FTP | other *** search
Wrap
Text File | 2002-03-15 | 26.1 KB | 738 lines | [ TEXT/Pyth]
# CLdialogs.py #-----------------------------------------------------------------||||||||||||-- # Copyright (c) 2001 Christopher Ariza. # # athenaCL comes with ABSOLUTELY NO WARRANTY; # for details see waranty information within athenaObj.py. # This is free software, and you are welcome to redistribute it under certain # conditions; for details see copyright information within athenaObj.py. #-----------------------------------------------------------------||||||||||||-- import sys, os, copy def update_visualMethod(): reload(os) if os.name == 'mac': import macfs osVisualMethod = 'mac' elif os.name == 'posix': try: import Tkinter Tkinter.Tk import tkFileDialog osVisualMethod = 'tkWin' except: osVisualMethod = 'text'#default, good on all platforms else: # all windows flavors try: import Tkinter Tkinter.Tk import tkFileDialog osVisualMethod = 'tkWin' except: osVisualMethod = 'text'#default, good on all platforms return osVisualMethod #-----------------------------------------------------------------||||||||||||-- ### utility functions # this version is different from that in athenaCL.py def print_topics(header, cmds, cmdlen, maxcol, outLine='off'): if header == '': ruler = '' else: ruler = '_' if cmds: max_len = 0 for name in cmds: if len(name) >= max_len: max_len = len(name) if cmdlen == 0: cmdlen = max_len + 2 # buffer space else: pass if header != '': print header if ruler != '': print ruler * 70 (cmds_per_line, junk) = divmod(maxcol, cmdlen) col = cmds_per_line for cmd in cmds: cmd = cmd.strip() if col == 0: print '' if outLine != 'off': ## only if special mode is desired if cmd != cmds[0]: # if not the first print (('%-'+`cmdlen`+'s') % ' '), # add white space col = (col+1) % cmds_per_line # shit col but dont skip cmd print (('%-'+`cmdlen`+'s') % cmd), col = (col+1) % cmds_per_line print '' #-----------------------------------------------------------------||||||||||||-- ### general dialogs def Message(string): string.strip() print string #-----------------------------------------------------------------||||||||||||-- def AskString(q_string, sessionType='terminal', parentGUI=None): if sessionType == 'terminal' or sessionType == 'IDLE': q_string = q_string + ' ' #this might have been causing spacing problems on return cariages a_string = raw_input(q_string) a_string.strip() return a_string elif sessionType == 'Tkinter': import dlgTk returnString = dlgTk.askstring("dlg", q_string, parent=parentGUI) if returnString == None: returnString = '' print '%s %s' % (q_string, returnString), # show user history return returnString def AskYesNoCancel(quary, default_selection=1, sessionType='terminal', parentGUI=None): if sessionType == 'terminal' or sessionType == 'IDLE': while 1: ### 1 for yes, 0 for no, -1 for cancel q_string = quary + '(y, n, or cancel): ' a_string = raw_input(q_string) status = -2 if a_string.find('-1') >= 0 or a_string.find('c') >= 0 or a_string.find('C') >= 0: status = -1 break elif a_string.find('1') >= 0 or a_string.find('y') >= 0 or a_string.find('Y') >= 0: status = 1 break elif a_string.find('0') >= 0 or a_string.find('n') >= 0 or a_string.find('N') >= 0: status = 0 break else: print ' unidentified input, please try again:' continue return status elif sessionType == 'Tkinter': import dlgTk while 1: ### 1 for yes, 0 for no, -1 for cancel quary = quary + '(y, n, or cancel): ' a_string = dlgTk.askstring("dlg", quary, parent=parentGUI) if a_string[-1:] == '\n\n': # watch for extra end-lines a_string = a_string[-1:] status = -2 if a_string == None: a_string = '' status = -1 # canceled break if a_string.find('-1') >= 0 or a_string.find('c') >= 0 or a_string.find('C') >= 0: status = -1 break elif a_string.find('1') >= 0 or a_string.find('y') >= 0 or a_string.find('Y') >= 0: status = 1 break elif a_string.find('0') >= 0 or a_string.find('n') >= 0 or a_string.find('N') >= 0: status = 0 break else: print ' unidentified input, please try again:' continue print '%s%s' % (quary, a_string), # show user history return status #-----------------------------------------------------------------||||||||||||-- ### general files service functioins def CheckDirPath(test_path): ### check for double_sep double_sep = os.sep + os.sep if test_path[-2:] == double_sep: test_path = test_path[:-2] return test_path def GetDirectory(prompt='please select a directory:', sample_dir=''): osVisualMethod = update_visualMethod() ### returns 0 if canceled or quit, otherwise 1 ### platform specific file dialogs. if osVisualMethod == 'mac': import macfs fsspec, ok = macfs.GetDirectory(prompt) if ok != 1: return '', 0 path = fsspec.as_pathname() os.path.normpath(path) return path, 1 ### platform specific file dialogs. if osVisualMethod == 'tkWin': import Tkinter import tkFileDialog tkTemp = Tkinter.Tk() tkTemp.withdraw() options = {'filetypes':[("directory", "*")], ## "dir" only shows directories, but are unable to select 'initialdir': sample_dir, 'title' : prompt, 'parent' : tkTemp} guiTemp = tkFileDialog.Open() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( pathToFile = guiTemp.show() # clean up gui mess del guiTemp tkTemp.destroy() # return path if pathToFile != '' and pathToFile != None: pathToFile = os.path.dirname(pathToFile) ### remove file name pathToFile = os.path.normpath(pathToFile) return pathToFile, 1 else: return '', 0 ### for all other platforms, osVisualMethod == text if sample_dir == '': current_dir = CheckDirPath(os.getcwd()) else: if os.path.isdir(sample_dir) != 1: # if this path is not a directory current_dir = CheckDirPath(os.getcwd()) else: current_dir = sample_dir final_path = '' while 1: #current_dir = CheckDirPath(current_dir) cwd_contents = os.listdir(current_dir) header = '%s' % current_dir #delete extra space here print_topics(header, cwd_contents, 0, 72) print prompt menu_items = 'change directory menu: enter name, .., path, cancel or select (c or s):' test_path = AskString(menu_items) final_path = '' ### scan for each of the options # if entry is s, return cwd if test_path == 's' or test_path == 'S': final_path = current_dir # go up to next higher directory, display contents if test_path == '..': pathValid = os.path.exists(current_dir) up_dir = os.path.dirname(current_dir) ### up_dir = CheckDirPath(up_dir) current_dir = up_dir continue # if entry is the name of a dir in the cwd, then display contents and make cwd if final_path == '': down_dir = os.path.join(current_dir, test_path) down_dir = os.path.normpath(down_dir) down_dir = CheckDirPath(down_dir) cwd_contents = os.listdir(current_dir) if test_path in cwd_contents: if os.path.isdir(down_dir) != 1: # if not a dir print ' to select a file, first select this directory by entering "s".' continue else: current_dir = down_dir continue # check if the user has entered a complete path if final_path == '': complete_path = CheckDirPath(test_path) if os.path.exists(complete_path) == 1 and os.path.isdir(complete_path) == 1: #true if is a directory.: current_dir = complete_path continue # final test if final_path == '': if test_path == 'c' or test_path == 'C': return '', 0 else: print ' %s not understood.' % test_path continue if os.path.exists(final_path) != 1: status = AskYesNoCancel(' this is not a valid path. try again? ') if status != 1: return '', 0 else: continue else: #ok = AskYesNoCancel(' CD: %s\n ' % final_path) #if ok == -1: final_path = os.path.normpath(final_path) return final_path, 1 def StandardPutFile(prompt='please name this file:', defaultFilename='name', defaultDirectory='', extension='*'): osVisualMethod = update_visualMethod() ### platform specific file dialogs. if osVisualMethod == 'mac': import macfs fsspec, ok = macfs.StandardPutFile(prompt, defaultFilename) if ok != 1: return '', 0 path = fsspec.as_pathname() ## check extension, add if missing path = os.path.normpath(path) return path, 1 ### platform specific file dialogs. if osVisualMethod == 'tkWin': import Tkinter import tkFileDialog tkTemp = Tkinter.Tk() tkTemp.withdraw() options = {'filetypes':[("all files", "*")], ### put extension here, but dont know if i need period or not 'initialdir': defaultDirectory, 'title' : prompt, 'parent' : tkTemp} guiTemp = tkFileDialog.SaveAs() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( path = guiTemp.show() # clean up gui mess del guiTemp tkTemp.destroy() # return path if path != '' and path != None: path = os.path.normpath(path) return path, 1 else: return '', 0 ### for all other platforms final_path = '' status = 0 directory = defaultDirectory while 1: ### get file name test_filename = AskString('%s' % prompt) if directory == '': directory = CheckDirPath(os.getcwd()) else: directory = CheckDirPath(directory) ### get directory status = AskYesNoCancel('%s\n save in this directory? ' % directory) if status == -1: #cancel break if status == 0: #no, get new directory path, ok = GetDirectory('', directory) if ok != 1: status = -1 break else: directory = path status = 1 if status == 1: ### test for existing file dir_contents = os.listdir(directory) if test_filename in dir_contents: ok = AskYesNoCancel('this file already exists. replace? ') if ok != 1: continue final_path = os.path.join(directory,test_filename) ok = AskYesNoCancel('%s\n save this file? ' % final_path) if ok == -1: status = -1 break elif ok == 0: continue elif ok == 1: status = 1 break final_path = os.path.normpath(final_path) return final_path, status def PromptGetFile(prompt='please select a file', directory=''): osVisualMethod = update_visualMethod() ### platform specific file dialogs. if osVisualMethod == 'mac': import macfs fsspec, ok = macfs.PromptGetFile(prompt) if ok != 1: return '', 0 path = fsspec.as_pathname() path = os.path.normpath(path) return path, 1 ### platform specific file dialogs. if osVisualMethod == 'tkWin': import Tkinter import tkFileDialog tkTemp = Tkinter.Tk() tkTemp.withdraw() options = {'filetypes':[("all files", "*")], 'initialdir': directory, 'title' : prompt, 'parent' : tkTemp} guiTemp = tkFileDialog.Open() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( path = guiTemp.show() # clean up gui mess del guiTemp tkTemp.destroy() # return path if path != '' and path != None: path = os.path.normpath(path) return path, 1 else: return '', 0 ### for all other platforms final_path = '' while 1: if directory == '': directory = CheckDirPath(os.getcwd()) else: directory = CheckDirPath(directory) header = '\n%s' % directory cwd_contents = os.listdir(directory) ### print_topics(header, cwd_contents, 0, 72) print prompt status = AskString('name file, change directory, or cancel? (f, cd, c):') if status == 'cd' or status == 'CD': try: path, ok = GetDirectory('', directory) except: print 'no such directory\n' continue if ok != 1: status = -1 break else: directory = path continue elif status == 'c' or status == 'C': break else: if status != 'f' and status != 'F': print ' unidentified input, please try again:' continue status = 0 while 1: test_filename = AskString('name file?') dir_contents = os.listdir(directory) if test_filename in dir_contents: test_path = directory + test_filename # only add to test ### check to see if file is a folder if os.path.isdir(test_path) == 1: #true if is a directory. ok = AskYesNoCancel('this is a directory, not a file. try again? ') if ok == 1: continue elif ok == 0: status = -2 break else: break final_path = os.path.join(directory,test_filename) # no os.sep needed break else: ok = AskYesNoCancel('no such file exists. try again? ') if ok == 1: continue elif ok == 0: status = -2 break else: break if status == -2: continue if final_path == '': status = -1 break else: ok = AskYesNoCancel('%s\n select this file? ' % final_path) if ok == -1: status = -1 break elif ok == 0: continue elif ok == 1: status = 1 break final_path = os.path.normpath(final_path) return final_path, status #-----------------------------------------------------------------||||||||||||-- ### general dispaly functions for athenaCL def userChooseFromList(prompt, choiceList, sessionType='terminal', parentGUI=None): p_list = choiceList p_list.sort() p_no = len(p_list) prompt = prompt + ' (name or number 1-%s):' % p_no name = AskString(prompt, sessionType, parentGUI) if name == None or name == '': return 0 if name in p_list: return name try: p_number = eval(name) except: return 0 if p_number <= p_no and p_number >= 1: ##not using actual indexes, but 1+ index name = p_list[p_number - 1] return name else: return 0 ## error message def graph_str(self, min, max, value): if min > max: high = min low = max rev = 1 else: high = max low = min rev = 0 percent = value / float(high) if percent < .025: str = '|+---------------------------------------|' elif percent >= .025 and percent < .050: str = '|-+--------------------------------------|' elif percent >= .050 and percent < .075: str = '|--+-------------------------------------|' elif percent >= .075 and percent < .100: str = '|---+------------------------------------|' elif percent >= .100 and percent < .125: str = '|----+-----------------------------------|' elif percent >= .125 and percent < .150: str = '|-----+----------------------------------|' elif percent >= .150 and percent < .175: str = '|------+---------------------------------|' elif percent >= .175 and percent < .200: str = '|-------+--------------------------------|' elif percent >= .200 and percent < .225: str = '|--------+-------------------------------|' elif percent >= .225 and percent < .250: str = '|---------+------------------------------|' elif percent >= .250 and percent < .275: str = '|----------+-----------------------------|' elif percent >= .275 and percent < .300: str = '|-----------+----------------------------|' elif percent >= .300 and percent < .325: str = '|------------+---------------------------|' elif percent >= .325 and percent < .350: str = '|-------------+--------------------------|' elif percent >= .350 and percent < .375: str = '|--------------+-------------------------|' elif percent >= .375 and percent < .400: str = '|---------------+------------------------|' elif percent >= .400 and percent < .425: str = '|----------------+-----------------------|' elif percent >= .425 and percent < .450: str = '|-----------------+----------------------|' elif percent >= .450 and percent < .475: str = '|------------------+---------------------|' elif percent >= .475 and percent < .500: str = '|-------------------+--------------------|' elif percent >= .500 and percent < .525: str = '|--------------------+-------------------|' elif percent >= .525 and percent < .550: str = '|---------------------+------------------|' elif percent >= .550 and percent < .575: str = '|----------------------+-----------------|' elif percent >= .575 and percent < .600: str = '|-----------------------+----------------|' elif percent >= .600 and percent < .625: str = '|------------------------+---------------|' elif percent >= .625 and percent < .650: str = '|-------------------------+--------------|' elif percent >= .650 and percent < .675: str = '|--------------------------+-------------|' elif percent >= .675 and percent < .700: str = '|---------------------------+------------|' elif percent >= .700 and percent < .725: str = '|----------------------------+-----------|' elif percent >= .725 and percent < .750: str = '|-----------------------------+----------|' elif percent >= .750 and percent < .775: str = '|------------------------------+---------|' elif percent >= .775 and percent < .800: str = '|-------------------------------+--------|' elif percent >= .800 and percent < .825: str = '|--------------------------------+-------|' elif percent >= .825 and percent < .850: str = '|---------------------------------+------|' elif percent >= .850 and percent < .875: str = '|----------------------------------+-----|' elif percent >= .875 and percent < .900: str = '|-----------------------------------+----|' elif percent >= .900 and percent < .925: str = '|------------------------------------+---|' elif percent >= .925 and percent < .950: str = '|-------------------------------------+--|' elif percent >= .950 and percent < .975: str = '|--------------------------------------+-|' elif percent >= .975: str = '|---------------------------------------+|' if rev == 1: l = list(str) l.reverse() str = '' for letter in l: str = str + letter ### this symbol may mot work on other systems! str = str.replace('+', '+') str = str.replace('-', '.') return str def getSalutation(localHour, localMin, cursToolFake='[] '): if localHour >= 3 and localHour < 5: salutation = '[good day.] ' elif localHour >= 5 and localHour < 12: salutation = '[good morning.] ' elif localHour >= 12 and localHour < 17: salutation = '[good afternoon.] ' elif localHour >= 17 and localHour < 22: salutation = '[good evening.] ' elif localHour >= 22 and localHour < 24: salutation = '[evening.] ' elif localHour >= 0 and localHour < 3: salutation = '[welcome.] ' clockHour = localHour%12 if clockHour == 0 and localHour == 12: clockHour = 12 ## default response: if localMin % 2 == 0 or localMin % 3 == 0 or localMin % 5 == 0 or localMin % 7 == 0 or localMin % 9 == 0: salutation = cursToolFake ### salutation = '[%i.%.2i] ' % (clockHour, localMin) if localHour == 4 or localHour == 16: if localMin == 20: salutation = '[praise to the most high!] ' return salutation #-----------------------------------------------------------------||||||||||||-- # strings for error messages! msgBadPmtrFormat = 'incorrect parameter format.\n' # need return carriage msgConfusedInput = 'incomprehensible input, please try again.' msgIncorrectEntry = ' incorrect entry. try again.' msgReturnCancel = '' #' .' msgModsNotFound = 'athenaCL cannot find all required modules. please enter the path of the "libATH" directory:' msgBadAthObj = ' there is a problem with this AthenaObject file. make sure an AthenaObject has been selected, then try (1) opening the file in a text editor and re-saving the file with the appropriate line endings or (2) restart athenaCL and try again.\n' msgSCselectX = 'please select SC X...' msgSCselectY = 'please select SC Y...' msgMCbadMapRange = ' incorrect map range. enter a start map, a comma, and an end map.' msgMCbadPosition = ' incorrect position entry. try again.' msgMCbadRankRange = ' incorrect rank range. enter a start rank, a comma, and an end rank.' msgMCerrorCreatingChord= ' there has been an error creating this chord, please try again.' msgMCenterRankMethod = 'enter ranking method: Smoothness, Uniformity or Balance? (s, u, or b):' msgPEnoNamedPE = 'no such PathEngine exists. enter "PEls" to see all names.\n' msgPMcreateFirst = 'create a multipath first: enter "PMn"\n' msgPInameGet = 'please name this PathInstance:' msgPIcreateFirst = 'create a PathInstance first: enter "PIn".\n' msgPImissingName = 'that PathInstance no longer exists: enter "PIo".\n' msgPIbadName = 'no such PathInstance exists. enter "PIls" to see all names.\n' msgPInameTaken = 'that PI name already exists, please choose another.' msgPVnotAvailable = 'no PV operations are available.\n' msgPVgroupMissingName = 'that PV Group no longer exists: enter "PVo".\n' msgPVbadName = 'no such PV Group exists. enter "PVls" to see all names.\n' msgPVnameTaken = 'that PV Group name already exists, please choose another.' msgTMbadName = 'no such TextureModule exists. enter "TMls" to see all names.\n' msgTIcreateFirst = 'create a TextureInstance first: enter "TIn".\n' msgTIselectFirst = 'select a TextureInstance first: enter "TIo".\n' msgTIbadName = 'no such TextureInstance exists. enter "TIls" to see all names\n' msgTImissingName = 'that TextureInstance no longer exists: enter "TIo".\n' msgTInameTaken = 'that TI name already exists, please choose another.' msgTIbadPmtrName = 'no such parameter exists: enter "TIv" to display parameters.\n' msgTCnameTaken = 'that TextureClone name already exists, please choose another.' msgTCcreateFirst = 'create a TextureClone first: enter "TCn".\n' msgTCbadName = 'no such TextureClone exists. enter "TCls" to see all names.\n' msgTCbadTimeEntry = ' a TextureClone cannot start before time 0. enter a more positive timeShift.' msgTTbadName = 'no such TextureTemperment exists. enter "TTls" to see all names.\n' msgCScreateFirst = 'create a score first. enter "CSsco".\n' #-----------------------------------------------------------------||||||||||||-- class Print_to_File: ''' temporarily redirects standard io (print functions) to a file''' def __init__(self, prompt='please name your file:', defaultFilename='name.sco', defaultDirectory='', extension='*'): # extension should have . in it (.sco) self.statusFlag = 0 while 1: try: self.file_path, ok = StandardPutFile(prompt, defaultFilename, defaultDirectory, extension) if ok == 0: self.statusFlag = -1 break self.statusFlag = 1 break except IOError: Message('error: file is busy!!\neither close the file or choose a new name.') def open_FileToPrint(self): self.stdout_init = sys.stdout ### save value of stdout for later sys.stdout = open(self.file_path, 'w') def get_fileNameDir(self): filename = os.path.basename(self.file_path) return filename, self.file_path def close_file(self): sys.stdout.close() #/* close std out */ sys.stdout = self.stdout_init ### return original value to stdout filename = os.path.basename(self.file_path) return filename, self.file_path class GetUserFile: 'class to facilitate writing scores to files' def __init__(self, prompt='please name your file:', defaultFilename='name.sco', defaultDirectory='', extension='*'): # extension should have . in it (.sco) self.statusFlag = 0 while 1: try: self.file_path, ok = StandardPutFile(prompt, defaultFilename, defaultDirectory, extension) if ok == 0: self.statusFlag = -1 break self.statusFlag = 1 break except IOError: Message('error: file is busy!!\neither close the file or choose a new name.') def get_fileNameDir(self): filename = os.path.basename(self.file_path) return filename, self.file_path def close_file(self): filename = os.path.basename(self.file_path) return filename, self.file_path if __name__ == '__main__': import athenaCL